<?php

namespace apiend\modules\mall\models;

use Yii;
use common\helpers\ArrayHelper;
use common\models\shop\ShopProduct;
use common\models\views\ViewSkuSpec;

/**
 * 商品规格信息模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class SpuSpec extends ViewSkuSpec {

    /**
     * @var string 选中的规格值
     */
    public $spec_values;

    /**
     * @var array 格式化后的规格值
     */
    private $_specValues = [];

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['product_id'], 'required'],
            [['product_id', 'goods_id'], 'integer'],
            [['spec_values'], 'string'],
            [['spec_values'], 'validateSku'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function validateSku($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $specString = $this->$attribute;
        if ($specString) {
            $specs = array_unique(explode(',', $specString));
            if (!empty($specs)) {
                $this->_specValues = $specs;
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function search() {
        if (!$this->validate()) {
            return $this->dumpError();
        }
        $query = static::find()->active()->andWhere([
            'product_id' => $this->product_id
        ]);
        $skus = $query->all();

        $product = ShopProduct::findOne($this->product_id);
        $specs = $product->typeSpecs;

        return static::formatSpecsGroup($skus, $specs);
    }

    /**
     * 分组格式化规格属性
     * @param array $data
     * @param array $checkSpecValues
     * @param integer $checkGoodsId
     * @return array
     */
    public static function formatSpecsGroup($data, $specs = []) {
        if (empty($data) || empty($specs)) {
            return [];
        }

        $fixedSpecId = 0;
        $groupSpecId = 0;
        $fixed_text = '';
        $group_text = '';

        foreach ($specs as $spec) {
            if ($fixedSpecId === 0) {
                $fixedSpecId = $spec->spec_id;
                $fixed_text = $spec->specName;
                continue;
            }
            $groupSpecId = $spec->spec_id;
            $group_text = $spec->specName;
        }

        $groupSpecValues = ArrayHelper::map($data, 'spec_value_id', 'spec_value', 'spec_id');
        if (count($groupSpecValues) !== 2) {
            return [];
        }
        $fixedSpecValues = $groupSpecValues[$fixedSpecId];

        $items = [];
        foreach ($fixedSpecValues as $fk => $fv) {
            $items[$fk] = [
                'name' => $fv,
                'items' => []
            ];
        }

        $result = ArrayHelper::index($data, 'spec_id', 'goods_id');

        foreach ($result as $goodslist) {
            $tempsvid = ArrayHelper::getValue($goodslist, [$fixedSpecId, 'spec_value_id'], 0);
            $goods = ArrayHelper::getValue($goodslist, $groupSpecId);
            $items[$tempsvid]['items'][] = $goods;
        }


        return [
            'fixed_text' => $fixed_text,
            'group_text' => $group_text,
            'specs' => array_values($items),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'name' => 'spec_value',
            'stock' => 'allowSales',
            'price' => 'memberPrice',
            'min',
            'goods_id',
            'product_id',
            'nums' => function() {
                return 0;
            },
        ];
    }

}
